#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "access.h"
#include "rmdir.h"
#include "usage.h"


void cmd_rmdir (int argument_count, char const * const * arguments)
{
	if (argument_count != 3)
		usage (arguments[0]);
	
	char const * path = arguments[2];
	
	int outcome = access (path, F_OK);
	if (outcome != 0) {
		outcome = errno;
		if (outcome == ENOENT) {
			fprintf (stderr, "[ee] `%s` does not exist\n", path);
			exit (1);
		} else
			die_with_errno (outcome);
	}
	
	struct stat stat_buf;
	outcome = stat (path, &stat_buf);
	if (outcome != 0)
		die_with_errno (errno);
	
	if (S_ISDIR (stat_buf.st_mode)){
		outcome = rmdir (path);
		if (outcome != 0)
			die_with_errno (outcome);
		else
			exit (0);
	}
	else {
		fprintf (stderr, "[ii] `%s` is not a folder\n", path);
		exit (1);
	}
}
